<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head>
  <meta charset="utf-8">
  <title>资源管理</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <link rel="stylesheet" th:href="@{/layui/css/layui.css}" media="all">
  <link rel="stylesheet" th:href="@{/adminui/dist/css/admin.css}" media="all">
  <link rel="stylesheet" th:href="@{/style/custom.css}" media="all">
</head>
<body>

<div class="layui-fluid">
  <div class="layui-card">
    <div class="layui-form layui-card-header layuiadmin-card-header-auto layui-form-pane" lay-filter="LAY-resource-front-form">
      <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label">资源名称</label>
          <div class="layui-input-block" id="parentId" style="width: 186px;margin-top: 1px;">
          </div>
        </div>
        <div class="layui-inline">
          <label class="layui-form-label">状态</label>
          <div class="layui-input-block">
            <select name="status" id="status" lay-search>
              <option value="">全部</option>
              <option th:each="map,idx:${statusList}" th:value="${map.key}" th:text="${map.value}"></option>
            </select>
          </div>
        </div>
        <div class="layui-inline">
          <button class="layui-btn layui-btn-normal layui-btn-sm" lay-submit lay-filter="LAY-resource-front-search">
            <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i> 搜索
          </button>
          <button class="layui-btn layui-btn-primary layui-btn-sm" lay-submit lay-filter="LAY-resource-front-reset">
            <i class="layui-icon layui-icon-refresh layuiadmin-button-btn"></i> 重置
          </button>
        </div>
      </div>
    </div>

    <div class="layui-card-body">
      <div class="layui-btn-group" style="padding-bottom: 10px;">
        <button class="layui-btn layui-btn-normal layui-btn-sm" id="btn-refresh">
          <i class="layui-icon">&#xe666;</i>刷新
        </button>
        <button class="layui-btn layui-btn-normal layui-btn-sm" id="btn-expand">
          <i class="layui-icon">&#xe624;</i>展开
        </button>
        <button class="layui-btn layui-btn-normal layui-btn-sm" id="btn-fold">
          <i class="layui-icon">&#xe67e;</i>折叠
        </button>
      </div>

      <table id="LAY-resource-tree-table" lay-filter="LAY-resource-tree-table"></table>

      <script type="text/html" id="resource-tree-table">
        <a sec:authorize="hasAuthority('sys:res:add')"  class="layui-btn layui-btn-normal layui-btn-xs" lay-event="add"><i class="layui-icon layui-icon-addition"></i>新增</a>
        <a class="layui-btn layui-btn-xs" lay-event="more">更多 <i class="layui-icon layui-icon-down"></i></a>
      </script>
      <script type="text/html" id="status-switchTpl">
        <input type="checkbox" disabled name="status" value="{{d.status}}" lay-skin="switch" lay-text="启用|禁用" {{ d.status== 'Y' ?'checked' : '' }}>
      </script>
    </div>
  </div>
</div>

<script th:src="@{/layui/layui.js}"></script>
<script>
  layui.config({
    base: '/'
  }).extend({
    // resource: 'modules/sys/resource',
    treeTb: 'extend/treetable-lay/treetable',
    xmSelect: 'extend/xm-select/dist/xm-select'
  }).use(['index', 'treeTb', 'xmSelect'], function () {
    let form = layui.form;
    let layer = layui.layer;
    let dropdown = layui.dropdown;
    let admin = layui.admin;
    let treeTab = layui.treeTb;
    let xmSelect = layui.xmSelect;

    //所属组织
    let parentId_select = xmSelect.render({
      el: '#parentId',
      name: 'parentId',
      // layVerify: 'required',
      layVerType: 'msg',
      //显示为text模式
      model: {label: {type: 'text'}},
      //单选模式
      radio: true,
      //选中关闭
      clickClose: true,
      toolbar: {
        show: true,
        list: ['CLEAR']
      },
      filterable: true,
      //树
      tree: {
        show: true,
        //非严格模式
        strict: false,
        //展开所有节点
        expandedKeys: true,
      },
      data: []
    });

    //加载组织机构下拉选
    admin.req({
      url: '/sys/resource/getSelectList',
      type: 'post',
      done: function (res) {
        parentId_select.update({
          data: res.data,
          autoRow: true,
        });
        //异步远程加载数据，需要重新设置
        parentId_select.changeExpandedKeys(true);
      }
    });

    let expand_ids = [];

    let renderTable = treeTab.render({
      elem: '#LAY-resource-tree-table',	//表格id
      url: '/sys/resource/getTreeTableList',
      method: 'POST',
      height: 'full-160',
      tree: {
        iconIndex: 1,
        isPidData: true,
        idName: 'resId',
        pidName: 'parentId',
        openName: 'open',// 是否默认展开的字段名
      },
      //设置一个空的，占个位置，不要会显示默认的
      toolbar: '<div></div>',
      defaultToolbar: ['filter'],
      page: false,
      cols: [
        [
          {type: 'numbers', fixed: 'left', title: '序号'},
          {field: 'title', title: '标题', minWidth: 160},
          {field: 'resId', title: '资源编码', width: 80},
          {field: 'name', title: '资源名称', minWidth: 120},
          {
            field: 'type', title: '类型', templet: function (d) {
              if (d.type == 'D') {
                return '<span class="layui-bg-green layui-badge-rim">目录</span>';
              } else if (d.type == 'M') {
                return '<span class="layui-bg-blue layui-badge-rim">菜单</span>';
              } else if (d.type == 'B') {
                return '<span class="layui-bg-orange layui-badge-rim">按钮</span>';
              } else {
                return '';
              }
            }, width: 63, unresize: true
          },
          {field: 'path', title: '链接地址', minWidth: 200},
          {field: 'mid', title: '权限标识', minWidth: 100},
          {field: 'icon', title: '图标', templet: function (d) {
              return '<i class="layui-icon ' + d.icon + '"></i>';
            }, width: 60},
          {field: 'seq', title: '排序', width: 60},
          {field: 'status', title: '状态', templet: '#status-switchTpl', unresize: true, width: 90},
          {field: 'updatedBy', title: '修改人', minWidth: 90},
          {title: '操作', width: 160, align: 'center', fixed: 'right', toolbar: '#resource-tree-table'}
        ]
      ],
      //数据渲染完的回调
      done: function (data) {
        expand_ids = [];
        //这里默认展开两级
        for (let i = 0; i < data.length; i++) {
          expand_ids.push(data[i].resId);
          let children = data[i].children;
          if (children && children.length > 0) {
            for (let a = 0; a < children.length; a++) {
              expand_ids.push(children[a].resId);
            }
          }
        }
        //关闭加载
        layer.closeAll('loading');

        for (let i = 0; i < expand_ids.length; i++) {
          renderTable.expand(expand_ids[i]);  // 展开指定节点
        }
      },
      style: 'margin-top:0;'
    });

    //监听工具条
    treeTab.on('tool(LAY-resource-tree-table)', function (obj) {
      let line_data = obj.data;
      if (obj.event === 'add') {
        layer.open({
          type: 2
          , title: '新增'
          , content: '/sys/resource/turn/edit?resId=' + line_data.resId
          , area: ['100%', '100%']
          , resize: false
          , btn: ['确认', '重置', '取消']
          , btnAlign: 'r'
          , maxmin: true
          , yes: function (index, layero) {
            let iframeWindow = window['layui-layer-iframe' + index]
                , submitID = 'LAY-resource-front-submit'
                , submit = layero.find('iframe').contents().find('#' + submitID);
            submit.trigger('click');
          }
          , btn2: function (index, layero) {
            let reset = layero.find('iframe').contents().find('#LAY-resource-front-reset');
            reset.trigger('click');
            return false; // 阻止关闭
          }
          , btn3: function (index, layero) {
            layer.close(index);
          }
          , end: function () {
            //数据刷新
            renderTable.refresh();
          }
        });
      } else if (obj.event === 'more') {
        let more = new Array();
        if([[${#authorization.expression('hasAuthority("sys:res:edit")')}]]) {
          more.push({
            title: '修改',
            id: 'edit',
            templet: '<i class="layui-icon layui-icon-edit"></i> 修改',
            href: '#'
          })
        }
        if([[${#authorization.expression('hasAuthority("sys:res:del")')}]]) {
          more.push({
            title: "删除",
            id: "del",
            templet: '<i class="layui-icon layui-icon-delete"></i> 删除',
            href: '#'
          })
        }

        //下拉菜单
        dropdown.render({
          elem: this, // 触发事件的 DOM 对象
          show: true, // 外部事件触发即显示
          align: 'left ' , // 右对齐弹出
          data: more,
          click: function (mdata) {
            if (mdata.id === "edit") {
              if ('root' === line_data.name) {
                layer.msg('根节点不允许修改！', {icon: 4, time: 1000, shade: [0.3, '#000', true]});
                return;
              }
              layer.open({
                type: 2
                , title: '修改'
                , content: '/sys/resource/turn/edit?id=' + line_data.id
                , area: ['100%', '100%']
                , resize: false
                , btn: ['确认', '重置', '取消']
                , btnAlign: 'r'
                , maxmin: true
                , yes: function (index, layero) {
                  let iframeWindow = window['layui-layer-iframe' + index]
                      , submitID = 'LAY-resource-front-submit'
                      , submit = layero.find('iframe').contents().find('#' + submitID);
                  submit.trigger('click');
                }
                , btn2: function (index, layero) {
                  let reset = layero.find('iframe').contents().find('#LAY-resource-front-reset');
                  reset.trigger('click');
                  return false; // 阻止关闭
                }
                , btn3: function (index, layero) {
                  layer.close(index);
                }
                , end: function () {
                  //数据刷新
                  renderTable.refresh();
                }
              });
            } else if (mdata.id === "del") {
              if ('root' === line_data.name) {
                layer.msg('根节点不允许删除！', {icon: 4, time: 1000, shade: [0.3, '#000', true]});
                return;
              }
              if (line_data.children && line_data.children.length > 0) {
                layer.msg('当前资源节点存在下级资源不允许删除！', {icon: 7, time: 1000, shade: [0.3, '#000', true]});
                return;
              }
              layer.confirm('真的删除行么？', function (index) {
                //提交 Ajax 成功后，更新表格中的数据
                admin.req({
                  url: '/sys/resource/del'
                  , type: 'post'
                  , contentType: 'application/json;charset=utf-8'
                  , data: JSON.stringify({"id": line_data.id})
                  , done: function (res) {
                    //执行成功
                    layer.msg(res.msg, {icon: 1});
                    renderTable.refresh(); //数据刷新
                    layer.close(index); //关闭弹层
                  }
                });
              });
            }
          }
        });
      }
    });

    layui.$('#btn-expand').click(function () {
      renderTable.expandAll('#LAY-resource-tree-table');
    });

    layui.$('#btn-fold').click(function () {
      renderTable.foldAll('#LAY-resource-tree-table');
    });

    layui.$('#btn-refresh').click(function () {
      renderTable.refresh();
    });

    //监听搜索
    form.on('submit(LAY-resource-front-search)', function (data) {
      let field = data.field;
      //执行重载
      treeTab.reload('LAY-resource-tree-table', {
        where: field,
        //数据渲染完的回调
        done: function (res) {
          expand_ids = [];
          //这里默认展开两级
          for (let i = 0; i < res.length; i++) {
            expand_ids.push(res[i].resId);
            let children = res[i].children;
            if (children && children.length > 0) {
              for (let a = 0; a < children.length; a++) {
                expand_ids.push(children[a].resId);
              }
            }
          }
          //关闭加载
          layer.closeAll('loading');

          for (let i = 0; i < expand_ids.length; i++) {
            renderTable.expand(expand_ids[i]);  // 展开指定节点
          }
        }
      });
    });
    // 监听重置
    form.on('submit(LAY-resource-front-reset)', function (data) {
      let field = data.field;
      for (let key of Object.keys(field)) {
        field[key] = '';
      }
      form.val("LAY-resource-front-form", field);

      parentId_select.setValue([]);
    });


  });
</script>
</body>
</html>
